﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;

namespace XcoAppSpaces.Security.Basic
{
	class UserStore
	{
		private const string defaultFilename = "XcoAppSpaces.Security.Basic_Users.xml";

		private string storePath;
		
		public UserStore(string storePath)
		{
			this.StorePath = storePath;
		}

		public string StorePath
		{
			get { return storePath; }
			set
			{
				if (value == null)
					storePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), defaultFilename);
				else
					storePath = value;
			}
		}

		public void Save(List<User> users)
		{
			XmlSerializer serializer = new XmlSerializer(typeof(List<User>));
			using (FileStream stream = File.Create(storePath))
			{
				serializer.Serialize(stream, users);
				stream.Close();
			}
		}

		public List<User> Load()
		{
			if (!File.Exists(storePath))
				return null;

			List<User> users = null;
			XmlSerializer serializer = new XmlSerializer(typeof(List<User>));
			using (FileStream stream = File.Open(storePath, FileMode.Open))
			{
				users = serializer.Deserialize(stream) as List<User>;
				stream.Close();
			}
			return users;
		}

		public void Clear()
		{
			if (File.Exists(storePath))
				File.Delete(storePath);
		}
	}
}
